package com.le.tester.imooc.ccmouse.socket;

import java.io.IOException;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 描述：client handler
 */
public class ClientHandler implements Runnable {

    private final Socket clientSocket;
    private final RequestHandler requestHandler;

    //构造函数最常用的功能，初始化

    public ClientHandler(Socket clientSocket, RequestHandler requestHandler) {
        this.clientSocket = clientSocket;
        this.requestHandler = requestHandler;
    }

    @Override
    public void run() {
        try (Scanner input = new Scanner(clientSocket.getInputStream())) {
            //第一个连接的socket除非遇到quit,
            //不然就会一直在这个循环里面，quit之后才会服务到另外的客户端
            while (true) {
                String request = input.nextLine();
                if ("quit".equals(request)) {
                    break;
                }
                String response = requestHandler.handler(request);
                //返回给客户端响应结果
                clientSocket.getOutputStream().write(response.getBytes(StandardCharsets.UTF_8));
            }
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
